//
//  ConPickViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/7/12.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConPickViewController.h"
#import "PickCommentView.h"
#import "PickUpNetwork.h"
#import "PersonNetWork.h"
#import "SZLAccountHelper.h"
#import "PickUpModel.h"
#import "PickUpCommentModel.h"
#import "MBProgressHUD+MJ.h"
#import <MJRefresh.h>
#import "GGIndicatorHud.h"
#import "TalkTableCell.h"
#import "SZLTabBarViewController.h"
#import "IQKeyboardManager.h"

@interface ConPickViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>{
 
    UITableView *tbView;
    NSMutableArray *dataArray;//捡漏内容数据组
    NSMutableArray *commentArray;//评论的数组
    UIView *conHeadView;
    UIImageView *headView;//顶部图片
    UITextField *print;//评论输入框
    UIButton *sendButton;//提交按钮
    UIView *keyboardTopView;//输入框view
    CGRect latestFrame;
    NSInteger pageNo;
    NSString *talkId;
    NSMutableArray *moreCommentsArray;
    NSIndexPath *commentBtnIndexPath;
    
    UIView *imageBottomView;
    UIImageView *bigImageView;
    CGPoint currentPoint;
    NSString *nickName;//昵称
}

@end

@implementation ConPickViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"人脉圈";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [tbView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

    pageNo = 1;
    dataArray = [[NSMutableArray alloc] init];
    commentArray = [[NSMutableArray alloc] init];
    moreCommentsArray = [NSMutableArray array];
    
    
    [self configHeaderView];
    [self createTableView];
    [self createCustomTextFiled];
    [tbView.mj_header beginRefreshing];
    imageBottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    imageBottomView.userInteractionEnabled = YES;
    [[UIApplication sharedApplication].delegate.window addSubview:imageBottomView];
    imageBottomView.backgroundColor = [UIColor blackColor];
    
    bigImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [imageBottomView addSubview:bigImageView];
    imageBottomView.hidden = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageBottomViewTap)];
    [imageBottomView addGestureRecognizer:tap];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;

    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
- (void)viewWillDisappear:(BOOL)animated {

    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;

}
- (void)imageBottomViewTap {
    imageBottomView.hidden = YES;
}
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}
- (void)keyboardWillShow:(NSNotification *)aNotification{
    NSDictionary* info = [aNotification userInfo];
    
    CGRect kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];//得
    keyboardTopView.y = kbSize.origin.y-110;
    
    CGPoint point =  tbView.contentOffset;
    point.y = point.y+kbSize.size.height/2;
    tbView.contentOffset = point;
    
}
- (void)keyboardWillHide:(NSNotification *)aNotification {
    NSDictionary* info = [aNotification userInfo];
    
    CGRect kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardTopView.frame = CGRectMake(0, ScreenH-SafeAreaTopHeight, ScreenW, 50);
    
    CGPoint point =  tbView.contentOffset;
    point.y = point.y-kbSize.size.height/2;
    tbView.contentOffset = point;
}
- (void)getPersonNickName {
    
    NSMutableDictionary *param  = [NSMutableDictionary dictionary];
    param[@"token"] = [SZLAccountHelper shareInstance].token;
    [PersonNetWork getPersonInfoWithParame:param response:^(BOOL success, NSString *msg, NSString *errorCode, PersonInfo *info) {
        if (success) {
            NSLog(@"info.nickName = %@",info.nickName);
        nickName = info.nickName;
        }else {
            
        }
    }];
}
- (void)loadData {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([SZLAccountHelper shareInstance].token) {
        param [@"token"]= [SZLAccountHelper shareInstance].token;
    }
    param [@"pageNo"] = @(pageNo);
//    [GGIndicatorHud showIndicatorInView:self.view];
    [PickUpNetwork getCommentDetailWithParame:param response:^(BOOL success, NSString *msg, NSMutableArray *arr) {
//        [GGIndicatorHud hideIndicatorHudInView:self.view];
        [tbView.mj_header endRefreshing];
        [tbView.mj_footer endRefreshing];
        if (success) {
            if (arr.count > 0) {
                pageNo++;
            } else {
                
                [tbView.mj_footer endRefreshingWithNoMoreData];
            }
            for (NSMutableDictionary *dict in arr) {
                PickUpModel *model = [[PickUpModel alloc] init];
                [model setModelWithDict:dict];
                [commentArray removeAllObjects];

                for (NSMutableDictionary *commentDict in model.ruleCommentsList) {
                    PickUpCommentModel *commentModel = [[PickUpCommentModel alloc] init];
                    [commentModel setModelWithDict:commentDict];
                    [commentArray addObject:commentModel];
                    
                }
                model.ruleCommentsList = [NSMutableArray arrayWithArray:commentArray];

                [dataArray addObject:model];
                
            }
            
            [tbView reloadData];
            
        }else {
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
    
}
- (void)createCustomTextFiled {
    
    print = [[UITextField alloc] initWithFrame:(CGRectMake(20, 10, ScreenW-100, 30))];
    print.placeholder = @"请输入评论内容";
    print.delegate = self;
    sendButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    sendButton.frame = CGRectMake(ScreenW-70, 10, 50, 30);
    [sendButton setTitle:@"提交" forState:(UIControlStateNormal)];
    [sendButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [sendButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    keyboardTopView = [[UIView alloc] initWithFrame:(CGRectMake(0, ScreenH, ScreenW, 50))];
    keyboardTopView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:keyboardTopView];
    
    [keyboardTopView addSubview:print];
    [keyboardTopView addSubview:sendButton];
}
//评论发表按钮
- (void)sendButtonClick:(UIButton *)btn {
    [print resignFirstResponder];
    
    if (print.text.length>0) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"token"] = [SZLAccountHelper shareInstance].token;
        param[@"id"] = talkId;
        param[@"ruleCommentContent"] = print.text;
        
        [PickUpNetwork getSendCommentWithParame:param response:^(BOOL success, NSString *msg, NSMutableArray *arr) {
            if (success) {
                
                TalkTableCell *cell = [tbView cellForRowAtIndexPath:commentBtnIndexPath];
                
                int a= [cell.pingNumLabel.text intValue]+1;
                cell.pingNumLabel.text = [NSString stringWithFormat:@"%d",a];
                
                PickUpModel *model = dataArray[commentBtnIndexPath.row];
                model.commentsNumber = [NSString stringWithFormat:@"%d",a];
                [dataArray replaceObjectAtIndex:commentBtnIndexPath.row withObject:model];
                
                 PickUpCommentModel *commentModel = [[PickUpCommentModel alloc] init];
                 commentModel.nickName = nickName;
                 commentModel.ruleCommentContent = print.text;
                //如果未超过三条
                if (![model.commentNumberStatus boolValue] || cell.lookMoreBtn.hidden == YES) {
                    [model.ruleCommentsList addObject:commentModel];
                    [dataArray replaceObjectAtIndex:commentBtnIndexPath.row withObject:model];
                    NSLog(@"没有超过三条");
                    [tbView reloadRowsAtIndexPaths:@[commentBtnIndexPath] withRowAnimation:UITableViewRowAnimationFade];
                }else {
                    
                    [self loadMoreCommentsListDataWithId:model.id indexPath:commentBtnIndexPath];
                }
                [MBProgressHUD showSuccess:@"评论成功!"];
                print.text = @"";
            }else {
                [MBProgressHUD showError:@"评论失败!" toView:self.view];
                print.text = @"";
            }
        }];
    }else {
        [MBProgressHUD showError:@"评论不能为空!" toView:self.view];
    }
    
}
- (void)createTableView {
    tbView = [[UITableView alloc] initWithFrame:(CGRectMake(0, 0, ScreenW, ScreenH-SafeAreaTopHeight-SafeAreaBottomHeight)) style:(UITableViewStylePlain)];
    tbView.backgroundColor = [UIColor whiteColor];
    tbView.delegate = self;
    tbView.dataSource = self;
    [tbView registerClass:[TalkTableCell class] forCellReuseIdentifier:@"TalkTableCell"];
    tbView.tableHeaderView = conHeadView;
    tbView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:tbView];
    tbView.rowHeight = UITableViewAutomaticDimension;
    tbView.estimatedRowHeight = 450.0f;
    tbView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pageNo = 1;
        [dataArray removeAllObjects];
        [self loadData];
        
    }];
    tbView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadData];
    }];
}

- (CGSize)AutoSizeWithStr:(NSString *)str textfont:(UIFont *)textfont size:(CGSize)size {
    return [str boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine |
            NSStringDrawingUsesLineFragmentOrigin |
            NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:textfont} context:nil].size;
    
}
//rows
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    PickUpModel *model = dataArray[indexPath.row];
    
    CGFloat titleHeight = [self AutoSizeWithStr:model.ruleTitle textfont:[UIFont systemFontOfSize:16] size:CGSizeMake(ScreenW-30, MAXFLOAT)].height;
    
    CGFloat contentHeight = [self AutoSizeWithStr:model.ruleContent textfont:[UIFont systemFontOfSize:14] size:CGSizeMake(ScreenW-30, MAXFLOAT)].height;
    
    if (model.pictureUrlList.count>0) {
        CGFloat imageWidth = (ScreenW-30-5*2)/3;
        
        if (model.ruleCommentsList.count > 0) {
            CGFloat labelBottom = 0;
            for (int i=0; i<model.ruleCommentsList.count; i++) {
                PickUpCommentModel *commentModel = model.ruleCommentsList[i];
                
                CGFloat commentHeight = [self AutoSizeWithStr:[NSString stringWithFormat:@"%@：%@",commentModel.nickName,commentModel.ruleCommentContent] textfont:[UIFont systemFontOfSize:14] size:CGSizeMake(ScreenW-50, MAXFLOAT)].height;
                
                labelBottom = labelBottom+5+commentHeight;
                
            }
            
            if ([model.commentNumberStatus boolValue] && model.ruleCommentsList.count < 4) {
                
                return 20+ labelBottom+5+10 +15+35+10 +titleHeight +10+contentHeight+10+imageWidth+10 +20+15+0.5;
                
            }
            
            return labelBottom+5+10 +15+35+10 +titleHeight +10+contentHeight+10+imageWidth+10 +20+15+0.5;
        }
        
        return 15+35+10 +titleHeight +10+contentHeight+10+imageWidth+10 +20+10+0.5;
    }
    if (model.ruleCommentsList.count > 0) {
        CGFloat labelBottom = 0;
        for (int i=0; i<model.ruleCommentsList.count; i++) {
            PickUpCommentModel *commentModel = model.ruleCommentsList[i];
            
            CGFloat commentHeight = [self AutoSizeWithStr:[NSString stringWithFormat:@"%@：%@",commentModel.nickName,commentModel.ruleCommentContent] textfont:[UIFont systemFontOfSize:14] size:CGSizeMake(ScreenW-50, MAXFLOAT)].height;
            
            labelBottom = labelBottom+5+commentHeight;
            
        }
        
        if ([model.commentNumberStatus boolValue] && model.ruleCommentsList.count < 4) {
            
            return 20+ labelBottom+5+10 + 15+35+10 +titleHeight +10+contentHeight+10 +20+15+0.5;
        }
        
        return labelBottom+5+10 + 15+35+10 +titleHeight +10+contentHeight+10 +20+15+0.5;
        
    }
    return 15+35+10 +titleHeight +10+contentHeight+10 +20+10+0.5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TalkTableCell *talkCell = [tableView dequeueReusableCellWithIdentifier:@"TalkTableCell"];
    talkCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    PickUpModel *model = dataArray[indexPath.row];
    [talkCell updateCellWithModel:model];
    
    __weak ConPickViewController *myself = self;
    [talkCell setLookMoreBlock:^(){
        
        [myself loadMoreCommentsListDataWithId:model.id indexPath:indexPath];
    }];
    
    [talkCell setImageTapBlock:^(UIImage *image){
        imageBottomView.hidden = NO;
        bigImageView.image = image;
        
        if (image.size.width/image.size.height > ScreenW/ScreenH) {
            bigImageView.frame = CGRectMake(0, (ScreenH-ScreenW*image.size.height/image.size.width)/2, ScreenW, ScreenW*image.size.height/image.size.width);
        } else {
            bigImageView.frame = CGRectMake((ScreenW-ScreenH*image.size.width/image.size.height)/2, 0, ScreenH*image.size.width/image.size.height, ScreenH);
        }
        
    }];
    
    __weak TalkTableCell *weakTalkCell = talkCell;
    
    talkCell.zanButtonBlock = ^(){
        
        [SZLAccountHelper shouldLogin];
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"token"] = [SZLAccountHelper shareInstance].token;
        param[@"id"] = model.id;
        [PickUpNetwork getZanWithParame:param response:^(BOOL success, NSString *msg) {
            if (success) {
                weakTalkCell.zanButton.selected = !weakTalkCell.zanButton.selected;
                if (weakTalkCell.zanButton.selected == YES) {
                    int a= [weakTalkCell.zanNumLabel.text intValue]+1;
                    weakTalkCell.zanNumLabel.text = [NSString stringWithFormat:@"%d",a];
                    [MBProgressHUD showSuccess:@"点赞成功!"];
                    
                    model.isNotPraise = @"1";
                    model.praise = [NSString stringWithFormat:@"%d",a];
                    [dataArray replaceObjectAtIndex:indexPath.row withObject:model];
                    
                }else {
                    int b= [weakTalkCell.zanNumLabel.text intValue]-1;
                    weakTalkCell.zanNumLabel.text = [NSString stringWithFormat:@"%d",b];
                    [MBProgressHUD showSuccess:@"点赞取消!"];
                    model.isNotPraise = @"0";
                    model.praise = [NSString stringWithFormat:@"%d",b];
                    [dataArray replaceObjectAtIndex:indexPath.row withObject:model];
                }
            }else {
                [MBProgressHUD showError:msg toView:self.view];
            }
        }];
        
    };
    //点击开始评论
    talkCell.pingButtonBlock = ^(){
        //如果没有登录
        if ([SZLAccountHelper shouldLogin]) return ;
        [self getPersonNickName];
        [print becomeFirstResponder];
        commentBtnIndexPath = indexPath;
        talkId = model.id;
    };
    
    return talkCell;
}
- (void)loadMoreCommentsListDataWithId:(NSString *)idStr indexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param [@"id"] = idStr;
    [PickUpNetwork getMoreCommentWithParame:param response:^(BOOL success, NSString *msg, NSMutableArray *arr) {
        if (success) {
            PickUpModel *model = dataArray[indexPath.row];
            
            [moreCommentsArray removeAllObjects];
            [moreCommentsArray addObjectsFromArray:model.ruleCommentsList];
            NSLog(@" %lu",(unsigned long)model.ruleCommentsList.count);
            for (NSMutableDictionary *commentDict in arr) {
                
                PickUpCommentModel *commentModel = [[PickUpCommentModel alloc] init];
                [commentModel setModelWithDict:commentDict];
                [moreCommentsArray addObject:commentModel];
            }
            model.ruleCommentsList = [NSMutableArray arrayWithArray:moreCommentsArray];
            
            [dataArray replaceObjectAtIndex:indexPath.row withObject:model];
            
            [tbView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (void)configHeaderView {
    
    conHeadView = [[UIImageView alloc] initWithFrame:(CGRectMake(0, 8, ScreenW, 208))];
    headView = [[UIImageView alloc] initWithFrame:(CGRectMake(0, 8, ScreenW, 200))];
    headView.contentMode = UIViewContentModeScaleAspectFill;
    headView.image = GetImage(@"headimage");
    [conHeadView addSubview:headView];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
